// -*- c-basic-offset: 2 default-tab-width: 2 indent-tabs-mode: t -*-
// vim: autoindent tabstop=2 noexpandtab shiftwidth=2 softtabstop=2
#include "Parser.h"

#undef PACKAGE_TARNAME
#undef PACKAGE_NAME
#undef PACKAGE_VERSION
#undef PACKAGE_STRING
#undef PACKAGE_BUGREPORT


#include "util.h"

using namespace R;

SourceParser::SourceParser() {
}

void ANTLR3_CDECL SourceParser::parseFile(const char* fName) {
	pANTLR3_INPUT_STREAM input;
	pANTLR3_COMMON_TOKEN_STREAM	tstream;
	RParser_script_return script;
	pRLexer lxr = this->lxr;
	pRParser psr = this->psr;

	// Openning stream
	input = antlr3AsciiFileStreamNew((pANTLR3_UINT8)fName);
	rerror_on(input == NULL, "Can't open/allocate input file: %s", fName);

	if(lxr == NULL) {
		this->lxr = lxr = RLexerNew(input);
		rerror_on(lxr == NULL, "Unable to allocate memory for parser");
	} else
		lxr->pLexer->setCharStream(lxr->pLexer, input);

	// Openning token stream
	tstream = antlr3CommonTokenStreamSourceNew(ANTLR3_SIZE_HINT, TOKENSOURCE(this->lxr));
	rerror_on(tstream == NULL, "Out of memory trying to allocate token stream");

	if(psr == NULL){
		this->psr = psr = RParserNew(tstream);
		rerror_on(psr == NULL, "Out of memory trying to allocate parser");
	} else
		psr->pParser->setTokenStream(psr->pParser, tstream->tstream);

	script = psr->script(psr);
	// printf("%s\n", script.tree->toStringTree(script.tree)->chars);

	// Free resource except lexer/parser
	tstream->free(tstream);
	// input->close(input); // if I close this stream there will be a bus error ... in the print not in the parsing.
}
